#!/usr/bin/env python3
"""
分析发现的Ford API端点，获取完整的Key Features数据
"""

import requests
import json
import time

def analyze_ford_apis():
    """分析Ford的API端点获取Key Features"""
    
    print("🔍 分析Ford API端点获取完整Key Features...")
    
    # 发现的关键API端点
    apis = [
        {
            'name': 'Ford Model JSON',
            'url': 'https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2.model.json'
        },
        {
            'name': 'Vehicle Model Load API (keyFeatures)',
            'url': 'https://www.servicescache.ford.com/api/vehicle-model/v1/load?locale=en_GB&retrieve=images,specs,featuresMkt,selectedMkt,featureImages,featureSpecs,keyFeatures,keyFeaturesModel,keyFeaturesWalkup,uscCodes,prices,featurePrices,content,packages&feature=&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-DH&displayContext=VISTA&suppressDisplayContext=true&namedConfig=default'
        },
        {
            'name': 'Vehicle Model Describe API (all configs)',
            'url': 'https://www.servicescache.ford.com/api/vehicle-model/v1/describe?locale=en_GB&retrieve=images,specs,featuresMkt,selectedMkt,featureImages,featureSpecs,keyFeatures,keyFeaturesModel,keyFeaturesWalkup,uscCodes,prices,featurePrices,content,packages&feature=&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-DH&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-JY&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-D4&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-D5&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-D3&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-EC&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMHQ_VS-EC&displayContext=VISTA&suppressDisplayContext=true&namedConfig=default'
        },
        {
            'name': 'Ford Configuration JSON',
            'url': 'https://www.ford.co.uk/content/guxeu-beta/uk/en_gb/configuration/applications-and-services/fc2-ice.model.json'
        }
    ]
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'en-GB,en;q=0.9',
        'Referer': 'https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin'
    }
    
    successful_apis = []
    
    for i, api in enumerate(apis):
        print(f"\n🌐 分析API {i+1}: {api['name']}")
        print(f"URL: {api['url']}")
        
        try:
            response = requests.get(api['url'], headers=headers, timeout=15)
            
            if response.status_code == 200:
                print(f"✅ 请求成功，状态码: {response.status_code}")
                
                try:
                    data = response.json()
                    print(f"✅ JSON解析成功，数据大小: {len(str(data))} 字符")
                    
                    # 搜索Key Features相关的数据
                    data_str = json.dumps(data, ensure_ascii=False).lower()
                    
                    # 检查是否包含我们期望的Key Features
                    expected_features = [
                        "alloy wheels",
                        "touchscreen", 
                        "keyless",
                        "led headlamps",
                        "quickclear",
                        "driver assistance",
                        "led rear lights",
                        "electrically operated",
                        "grille",
                        "dual-zone",
                        "sensico",
                        "manual 4-way",
                        "parking sensors",
                        "lane-keeping",
                        "pre-collision",
                        "tft",
                        "thatcham"
                    ]
                    
                    found_features = []
                    for feature in expected_features:
                        if feature in data_str:
                            found_features.append(feature)
                    
                    print(f"🎯 找到的相关特性关键词: {len(found_features)}/{len(expected_features)}")
                    print(f"   匹配的关键词: {found_features}")
                    
                    if len(found_features) > 5:  # 如果找到超过5个关键词，认为这是有希望的API
                        print(f"🎉 这是一个有希望的API！")
                        
                        successful_apis.append({
                            'name': api['name'],
                            'url': api['url'],
                            'data': data,
                            'found_features': found_features
                        })
                        
                        # 保存详细数据
                        filename = f"./release/api_detailed_{i+1}_{api['name'].replace(' ', '_')}.json"
                        with open(filename, 'w', encoding='utf-8') as f:
                            json.dump({
                                'api_name': api['name'],
                                'api_url': api['url'],
                                'found_features': found_features,
                                'response_data': data
                            }, f, ensure_ascii=False, indent=2)
                        
                        print(f"💾 详细数据已保存到: {filename}")
                    
                except json.JSONDecodeError as e:
                    print(f"❌ JSON解析失败: {e}")
                    # 尝试作为文本处理
                    text_content = response.text
                    print(f"响应内容类型: text, 长度: {len(text_content)} 字符")
                    
                    if len(text_content) < 500:
                        print(f"响应内容: {text_content}")
                    
            else:
                print(f"❌ 请求失败，状态码: {response.status_code}")
                print(f"响应内容: {response.text[:200]}")
                
        except Exception as e:
            print(f"❌ API请求异常: {e}")
        
        time.sleep(1)  # 避免请求过于频繁
    
    # 分析最有希望的API
    if successful_apis:
        print(f"\n🎉 找到 {len(successful_apis)} 个包含Key Features的API:")
        
        for i, api in enumerate(successful_apis):
            print(f"\n分析API {i+1}: {api['name']}")
            print(f"包含特性关键词: {api['found_features']}")
            
            # 深度分析数据结构
            data = api['data']
            
            def find_key_features_data(obj, path="", depth=0):
                """递归搜索Key Features数据"""
                results = []
                
                if depth > 10:  # 防止无限递归
                    return results
                
                if isinstance(obj, dict):
                    for key, value in obj.items():
                        key_lower = key.lower()
                        
                        # 查找Key Features相关的键
                        if any(kw in key_lower for kw in ['feature', 'spec', 'equipment', 'option']):
                            if isinstance(value, (list, dict)):
                                results.append({
                                    'path': f"{path}.{key}",
                                    'type': type(value).__name__,
                                    'data': value,
                                    'size': len(value) if isinstance(value, (list, dict)) else 0
                                })
                        
                        # 递归搜索
                        results.extend(find_key_features_data(value, f"{path}.{key}", depth + 1))
                
                elif isinstance(obj, list):
                    for idx, item in enumerate(obj):
                        results.extend(find_key_features_data(item, f"{path}[{idx}]", depth + 1))
                
                return results
            
            feature_data = find_key_features_data(data)
            
            print(f"找到 {len(feature_data)} 个可能的特性数据路径:")
            
            for j, fd in enumerate(feature_data[:5]):  # 只显示前5个
                print(f"  {j+1}. 路径: {fd['path']}")
                print(f"     类型: {fd['type']}, 大小: {fd['size']}")
                
                # 如果是列表，尝试显示内容
                if isinstance(fd['data'], list) and fd['data']:
                    print(f"     内容示例: {str(fd['data'][:3])[:100]}...")
                elif isinstance(fd['data'], dict):
                    sample_keys = list(fd['data'].keys())[:3]
                    print(f"     键示例: {sample_keys}")
            
            # 特别查找Titanium相关的数据
            titanium_data = []
            
            def find_titanium_data(obj, path=""):
                results = []
                if isinstance(obj, dict):
                    for key, value in obj.items():
                        if 'titanium' in key.lower() or (isinstance(value, dict) and 'titanium' in str(value).lower()):
                            results.append({
                                'path': f"{path}.{key}",
                                'data': value
                            })
                        results.extend(find_titanium_data(value, f"{path}.{key}"))
                elif isinstance(obj, list):
                    for idx, item in enumerate(obj):
                        results.extend(find_titanium_data(item, f"{path}[{idx}]"))
                return results
            
            titanium_data = find_titanium_data(data)
            
            if titanium_data:
                print(f"\n🎯 找到 {len(titanium_data)} 个Titanium相关数据:")
                for td in titanium_data[:3]:
                    print(f"  路径: {td['path']}")
                    print(f"  数据: {str(td['data'])[:200]}...")
        
        # 保存分析结果
        result_summary = {
            'total_apis_analyzed': len(apis),
            'successful_apis': len(successful_apis),
            'api_details': [
                {
                    'name': api['name'],
                    'url': api['url'],
                    'found_features_count': len(api['found_features']),
                    'found_features': api['found_features']
                } for api in successful_apis
            ]
        }
        
        with open('./release/api_analysis_summary.json', 'w', encoding='utf-8') as f:
            json.dump(result_summary, f, ensure_ascii=False, indent=2)
        
        print(f"\n💾 API分析总结已保存到: ./release/api_analysis_summary.json")
        
    else:
        print(f"\n❌ 未找到包含足够Key Features数据的API")
    
    return successful_apis

if __name__ == "__main__":
    analyze_ford_apis()
